import config from '@/config'
import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import pinia from '@/components/pinia'
import { useEnvStore } from '@/stores/env'
import { isArray } from 'lodash'

let loadingInstance

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
  switch (code) {
    case 403:
      router.push({ path: '/403' })
      break
    default:
      ElMessage.warning(msg || `后端接口${code}异常`)
      break
  }
}

/**
 * @description axios初始化
 */
const instance = axios.create({
  baseURL: useEnvStore(pinia).baseURL,
  timeout: config.requestTimeout,
})

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(
  (config) => {
    if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8')
      config.data = qs.stringify(config.data)

    if (config.method === 'get') {
      //  给data赋值以绕过if判断
      config.data = true
      config.paramsSerializer = function (params) {
        //对于get 参数 为数组时进行处理；解决产生参数为   xxxx[]:xxxx   的情况
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }

    if (config.headers.contentType == undefined) {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    } else {
      config.headers['Content-Type'] = config.headers.contentType
      delete config.headers.contentType
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    const { data, status } = response
    const { message } = data
    // 操作正常Code数组
    const codeVerificationArray = isArray(config.successCode) ? [...config.successCode] : [...[config.successCode]]
    // 是否操作正常
    if (codeVerificationArray.includes(status)) {
      return data
    } else {
      handleCode(status, message)
      return Promise.reject('请求异常拦截:' + JSON.stringify({ status, message }) || 'Error')
    }
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()
    const { response, message } = error
    if (error.response && error.response.data) {
      const { status, data } = response
      handleCode(status, data.message || message)
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '后端接口' + code + '异常'
      }
      ElMessage.warning(message || `后端接口未知异常`)
      return Promise.reject(error)
    }
  },
)

export default instance
